import React, { useState, useEffect } from 'react';
import styles from './index.less';
import {
  Button,
  Input,
  Table,
  Select,
  Modal,
  InputNumber,
  Form,
  Upload,
  message,
} from 'antd';
import CardCommon from '@/compontents/cardCommon';
import lhTool from 'lh-tool';
import api from '@/http/api';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import md5 from 'md5';

const { uTicketList, uTicketAdd, uTicketDelete, uTicketUpdate } = api;
const { Option } = Select;
const { confirm } = Modal;

export default (props: any) => {
  // 表格
  const [list, setList] = useState([]);
  const [pageNo, setPageNo] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  // 上传图片
  const [fileList1, seFileList1]: any = useState([]);

  // 商铺ID
  const { uBusinessId } = props.history.location.state;
  // 学校id
  const { schoolId } = JSON.parse(sessionStorage.info).userInfo;
  // 学校列表
  const [schoolList, setSchoolList] = useState([]);
  // 新增编辑弹框
  const [showAdd, setShowAdd] = useState(false);
  // 是否新增
  const [isAdd, setIsAdd] = useState(true);
  const [initData, setInitData]: any = useState({});
  // 表单样式
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 16 },
  };
  const tailLayout = {
    wrapperCol: { offset: 17, span: 16 },
  };
  const columns: any = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      width: 100,
      render: (text: any, record: any, index: any) => `${index + 1}`,
    },
    {
      title: '套餐内容',
      dataIndex: 'content',
    },
    {
      title: '套餐价格(元)',
      dataIndex: 'price',
    },
    {
      title: '套餐原价(元)',
      dataIndex: 'priceOld',
    },
    {
      title: '销量',
      dataIndex: 'num',
    },
    {
      title: '券总量',
      dataIndex: 'numTotal',
    },
    {
      title: '操作',
      dataIndex: 'handle',
      width: 200,
      render: (v1: any, v2: any) => (
        <div>
          <Button
            onClick={() => {
              add(v2);
            }}
            size="small"
            type="primary"
          >
            编辑
          </Button>
          <Button
            onClick={() => {
              deleteR(v2);
            }}
            style={{ marginLeft: 10 }}
            size="small"
            danger
            type="primary"
          >
            删除
          </Button>
        </div>
      ),
    },
  ];
  useEffect(() => {
    getList(pageNo, pageSize, uBusinessId);
  }, []);
  // 表格列表
  const getList = (pageNo: Number, pageSize: Number, uBusinessId: Number) => {
    uTicketList({
      pageNo,
      pageSize,
      uBusinessId,
    }).then((res: any) => {
      const { list, total } = res.data;
      setList(list);
      setTotal(total);
    });
  };
  // 分页改变
  const pageChange = (pageNo: any, pageSize: any) => {
    setPageNo(pageNo);
    setPageSize(pageSize);
    getList(pageNo, pageSize, uBusinessId);
  };
  const handleCancel = () => {
    setShowAdd(false);
  };
  // 点击新增编辑
  const add = (row: any) => {
    const { id, src } = row;
    setIsAdd(id ? false : true);
    if (id) {
      // 编辑
      setShowAdd(true);
      setInitData(row);
      seFileList1([
        {
          uid: 1,
          url: src,
        },
      ]);
    } else {
      // 新增
      setShowAdd(true);
    }
  };
  const onFinish = (v: any) => {
    if (!fileList1.length) {
      message.error('请上传套餐图片');
    } else {
      const { content, price, priceOld, numTotal } = v;
      const src = fileList1[0].url;
      if (isAdd) {
        uTicketAdd({
          content,
          price,
          priceOld,
          numTotal,
          uSchoolId: schoolId,
          uBusinessId,
          src,
        }).then(_ => {
          setShowAdd(false);
          getList(pageNo, pageSize, uBusinessId);
        });
      } else {
        const { id } = initData;
        uTicketUpdate({
          content,
          price,
          priceOld,
          numTotal,
          id,
          uBusinessId,
          src,
        }).then(_ => {
          setShowAdd(false);
          getList(pageNo, pageSize, uBusinessId);
        });
      }
    }
  };
  const deleteR = (row: any) => {
    const { id } = row;
    confirm({
      title: '提示',
      icon: <ExclamationCircleOutlined />,
      content: '确定删除吗？',
      onOk() {
        uTicketDelete({ id, uBusinessId }).then(_ => {
          getList(pageNo, pageSize, uBusinessId);
        });
      },
    });
  };
  // 上传图片
  const onchange1 = (e: any) => {
    const fileLists = e.fileList;
    const len = fileLists.length;
    if (e.file.status === 'done') {
      const list: any = [...fileList1].splice(0, len - 1);
      list.push({
        uid: new Date().getTime(),
        url: e.file.response.data.src,
      });
      seFileList1(list);
    } else {
      seFileList1(fileLists);
    }
  };

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传</div>
    </div>
  );
  return (
    <CardCommon>
      <div className={styles.wrap}>
        <div className={styles.tool}>
          <Button
            onClick={() => {
              add({});
            }}
            type="primary"
          >
            新增
          </Button>
        </div>
        <Table
          dataSource={list}
          columns={columns}
          pagination={{
            showQuickJumper: true,
            total,
            size: 'small',
            onChange: pageChange,
            showTotal: () => {
              return `总共 ${total} 条记录`;
            },
          }}
        />
        <Modal
          title={isAdd ? '新增商铺管理员' : '编辑商铺管理员'}
          visible={showAdd}
          onCancel={handleCancel}
          footer={null}
          destroyOnClose
        >
          <Form
            className={styles.form}
            {...layout}
            name="basic"
            initialValues={{ remember: true }}
            onFinish={onFinish}
          >
            <Form.Item
              label="套餐内容"
              name="content"
              rules={[{ required: true, message: '请输入套餐内容' }]}
              initialValue={isAdd ? '' : initData.content}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="套餐图片"
              name="src"
              rules={[{ required: false, message: '请上传套餐图片' }]}
            >
              <Upload
                action={process.env.apiUrl + 'upload/image'}
                listType="picture-card"
                fileList={fileList1}
                // onPreview={this.handlePreview}
                onChange={onchange1}
              >
                {fileList1.length >= 1 ? null : uploadButton}
              </Upload>
            </Form.Item>
            <Form.Item
              label="套餐价格"
              name="price"
              rules={[{ required: true, message: '请输入套餐价格' }]}
              initialValue={isAdd ? '' : initData.price}
            >
              <InputNumber min={0.1} />
            </Form.Item>
            <Form.Item
              label="套餐原价"
              name="priceOld"
              rules={[{ required: true, message: '请输入套餐原价' }]}
              initialValue={isAdd ? '' : initData.priceOld}
            >
              <InputNumber min={0.1} />
            </Form.Item>
            <Form.Item
              label="券总量"
              name="numTotal"
              rules={[{ required: true, message: '请输入券总量' }]}
              initialValue={isAdd ? '' : initData.numTotal}
            >
              <InputNumber min={1} />
            </Form.Item>
            <Form.Item {...tailLayout}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </CardCommon>
  );
};
